﻿using System;
using System.IO;
using System.Text.RegularExpressions;
using System.Threading;
using System.Windows.Forms;
using FinalFantasy6Randomizer.Properties;

namespace FinalFantasy6Randomizer
{
    public partial class MainForm : Form
    {
        private Thread checkUpdateThread;
        public static string Version = "7";

        public MainForm()
        {
            InitializeComponent();
        }

        private void RunCheckUpdate()
        {
            checkUpdateThread = new Thread(CheckUpdate);
            checkUpdateThread.SetApartmentState(ApartmentState.STA);
            checkUpdateThread.Start();
        }

        private void CheckUpdate()
        {
            var response = GetResponse("https://ff6randomizer.codeplex.com/");

            if (string.IsNullOrWhiteSpace(response))
                return;

            var pattern = "<TD>Final Fantasy VI Randomizer v(?<version>\\S+) </TD>";
            var match = Regex.Match(response, pattern);

            if (match.Success)
            {
                var currentVersion = match.Groups["version"].Value;
                int versionNum;
                int currentVersionNum; 

                if (int.TryParse(Version, out versionNum) && int.TryParse(currentVersion, out currentVersionNum))
                {
                    if (int.Parse(Version) < int.Parse(currentVersion))
                    {
                        var result =
                            MessageBox.Show(
                                string.Format("You have v{0} and the current version is v{1}. Would you like to update?", Version, currentVersion), "Version Update", MessageBoxButtons.YesNo);

                        if (result == DialogResult.Yes)
                            Help.ShowHelp(null, "https://ff6randomizer.codeplex.com/");
                    }
                }
                else
                {
                    if (Version != currentVersion)
                    {
                        var result =
                            MessageBox.Show(
                                string.Format("You have v{0} and the current version is v{1}. Would you like to update?", Version, currentVersion), "Version Update", MessageBoxButtons.YesNo);

                        if (result == DialogResult.Yes)
                            Help.ShowHelp(null, "https://ff6randomizer.codeplex.com/");
                    }
                }
            }

        }

        private static string GetResponse(string address)
        {
            if (!address.Contains("ff6randomizer.codeplex.com"))
                return "";

            var webBrowser = new WebBrowser { ScrollBarsEnabled = false, ScriptErrorsSuppressed = true };
            webBrowser.Navigate(address);
            while (webBrowser.ReadyState != WebBrowserReadyState.Complete) { Application.DoEvents(); }

            return webBrowser.Document.Body.InnerHtml;
        }

        private void browse_Click(object sender, EventArgs e)
        {
            var info = new FileInfo(filename.Text.Replace("<seed>", ""));
            var saveFileDialog = new SaveFileDialog { Filter = "All files (*.*)|*.*", FilterIndex = 2, RestoreDirectory = true, InitialDirectory = info.DirectoryName, FileName = info.Name };

            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {
                filename.Text = saveFileDialog.FileName;
                MessageBox.Show("Remember to hit \"create\" to create the rom.", "Remember to create the rom!", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1);
            }
        }

        private void create_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(seed.Text))
                seed.Text = string.Format("{0:0000000}", (new SeedRandom()).Next(10000000));

            ClearOutput();

            int parsedSeed;

            if (!int.TryParse(seed.Text, out parsedSeed))
            {
                MessageBox.Show("Seed must be numeric or blank.", "Seed Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                WriteOutput("Seed must be numeric or blank.");
            }
            else
            {
                var randomizer = new Randomizer(parsedSeed);
                randomizer.CreateRom(filename.Text);

                WriteOutput(string.Format("Done!{1}{1}{1}Seed: {0:0000000}{1}{1}", parsedSeed, Environment.NewLine));

                if (clearSeed.Checked)
                {
                    seed.Text = "";
                }
            }

        }

        private void ClearOutput()
        {
            output.Text = "";
        }

        private void WriteOutput(string text)
        {
            output.Text += text;         
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            Text = string.Format("Final Fantasy VI Randomizer v{0}", Version);
            clearSeed.Checked = Settings.Default.ClearSeed;
            filename.Text = Settings.Default.OutputFile;
            RunCheckUpdate();
        }

        private void filename_TextChanged(object sender, EventArgs e)
        {
            Settings.Default.OutputFile = filename.Text;
            Settings.Default.Save();
        }

        private void config_Click(object sender, EventArgs e)
        {
            using (var configForm = new ConfigForm())
            {
                configForm.ShowDialog();
            }
        }

        private void clearSeed_CheckedChanged(object sender, EventArgs e)
        {
            Settings.Default.ClearSeed = clearSeed.Checked;
            Settings.Default.Save();
        }

        private void filename_Leave(object sender, EventArgs e)
        {
            if (!filename.Text.Contains("."))
            {
                filename.Text += ".sfc";
            }
        }
    }
}
